<?php

class NavController extends Controller
{
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

    public function accessRules()
    {
        return array(
            array('deny',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index', 'create', 'update', 'delete'),
                'users'=>array('?'),
            ),
        );
    }

	public function actionCreate()
	{
		$model = new Nav(self::$CREATE);

        // 设置是否激活的默认值
        $model->nav_is_active = 1;

        $this->performAjaxValidation($model);

		if(isset($_POST['Nav']))
		{
			$model->attributes = $_POST['Nav'];
			if($model->save())
				BlogTool::successRedirect('添加导航成功', 'nav/index');
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
		$model=$this->loadModel($id, self::$UPDATE);

        $this->performAjaxValidation($model);

		if(isset($_POST['Nav']))
		{
			$model->attributes = $_POST['Nav'];
			if($model->save())
                BlogTool::successRedirect('修改导航成功', 'nav/index');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete($id)
	{
        $this->loadModel($id, self::$DELETE)->delete();
        BlogTool::successRedirect('删除导航成功', 'nav/index');
	}

	public function actionIndex()
	{
        $model = new Nav();

        $criteria = new CDbCriteria();
        $criteria->select = 'id, nav_name, nav_sort, nav_is_active';
        $criteria->order = 'nav_sort asc, id desc';

        // 分页
        $pages = parent::showPager($model, $criteria);

        $data = $model->findAll($criteria);

        // 排序导航
        if(isset($_POST['send']))
        {
            foreach($_POST['ids'] as $k=>$v)
            {
                $nav = Nav::model()->findByPk($v);
                $nav->nav_sort = $_POST['sortNum'][$k];
                $nav->save();
            }
            BlogTool::successRedirect(null, array('nav/index'));
        }

		$this->render('index',array(
			'data'=>$data,
            'pager'=>$pages
		));
	}

	public function loadModel($id, $sec)
	{
		$nav = new Nav($sec);
        $model = $nav->findByPk((int)$id);

		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='nav-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
